﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// 场景控制器基类
/// </summary>
public abstract class BaseSceneController
{
    public Scene Scene { get; private set; }

    private GameObject cameraRoot;
    private GameObject envRoot;

    private string lastCamera;
    private string curCamera;
    protected Dictionary<string, GameObject> cameraDict;

    /// <summary>
    /// 绑定场景
    /// </summary>
    /// <param name="scene"></param>
    public void BindScene(Scene scene)
    {
        Scene = scene;
        var rootGos = scene.GetRootGameObjects();
        for (int i = 0; i < rootGos.Length; i++)
        {
            CheckRootGameObjects(rootGos[i]);
        }
        OnInit();
    }

    private void CheckRootGameObjects(GameObject rootGo)
    {
        switch (rootGo.name)
        {
            case "Main Camera":
                rootGo.SetActive(false);
                break;
            case "VCameras":
                cameraRoot = rootGo;
                cameraDict = new Dictionary<string, GameObject>();
                for (int j = 0; j < rootGo.transform.childCount; j++)
                {
                    var child = rootGo.transform.GetChild(j).gameObject;
                    var key = child.name;
                    cameraDict.Add(key, child);
                }
                break;
            case "Env":
                envRoot = rootGo;
                break;
            default:
                break;
        }
    }

    #region 相机操作

    /// <summary>
    /// 打开相机
    /// </summary>
    /// <param name="cameraName"></param>
    public void ChangeCamera(string cameraName)
    {
        if (!string.IsNullOrEmpty(curCamera))
        {
            if(curCamera == cameraName)
            {
                return;
            }
            cameraDict[curCamera].SetActive(false);
            lastCamera = curCamera;
        }
        cameraDict[cameraName].SetActive(true);
        curCamera = cameraName;
    }

    /// <summary>
    /// 返回上一个相机
    /// </summary>
    public void BackCamera()
    {
        if (string.IsNullOrEmpty(lastCamera))
        {
            return;
        }
        ChangeCamera(lastCamera);
    }

    /// <summary>
    /// 修改相机根节点
    /// </summary>
    /// <param name="open"></param>
    public void ChangeCameraRoot(bool open)
    {
        cameraRoot.SetActive(open);
    }

    #endregion

    public abstract void OnInit();
    public abstract void OnRelease();

    public virtual void OnEnable() 
    {
        cameraRoot.SetActive(true);
        envRoot.SetActive(true);
    }

    public virtual void OnDisable() 
    {
        cameraRoot.SetActive(false);
        envRoot.SetActive(false);
    }
}
